import ReactECharts from 'echarts-for-react';
import { useMemo } from 'react';
import './ChartContainer.css';

const ChartContainer = ({ data }) => {
  // 使用 useMemo 来缓存图表配置，避免不必要的重新渲染
  const chartOption = useMemo(() => {
    // 检查是否有有效的图表数据
    const hasValidChartData = data && (
      (data.series && data.series.length > 0) ||
      (data.xAxis && data.xAxis.data && data.xAxis.data.length > 0) ||
      (data.title && data.title.text)
    );

    if (!hasValidChartData) {
      return null;
    }

    // 如果没有提供完整的配置，显示占位符
    if (!data.series || data.series.length === 0) {
      return {
        title: { text: '图表数据不完整' },
        xAxis: { type: 'category', data: [] },
        yAxis: { type: 'value' },
        series: [],
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        }
      };
    }

    return {
      title: data.title || { text: '数据图表' },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      legend: {
        data: data.series?.map(s => s.name) || []
      },
      xAxis: data.xAxis || {
        type: 'category',
        data: []
      },
      yAxis: data.yAxis || {
        type: 'value'
      },
      series: data.series || [],
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      }
    };
  }, [data]);

  if (!chartOption) {
    return (
      <div className="chart-container">
        <div className="chart-placeholder">
          <div className="placeholder-icon">📊</div>
          <div className="placeholder-text">暂无图表数据</div>
        </div>
      </div>
    );
  }

  return (
    <div className="chart-container">
      <ReactECharts 
        option={chartOption} 
        style={{ height: '300px', width: '100%' }}
        opts={{ renderer: 'canvas' }}
      />
    </div>
  );
};

export default ChartContainer;
